<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" :noprintDownShow="true">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="lookBtn(row.row.row)">历史预警
          </el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="deleteBtn(row.row.row)">删除
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <span :class="state.addModal ? 'listInfoBtn active' : 'listInfoBtn'" @click="addBtn('mul')">
          <svg-icon :class="state.addModal ? 'active' : ''" class-name="search-icon" icon-class="xinzeng" />
          新增
        </span>
        <span :class="'listInfoBtn'" @click="deleteBtn('mul')">
          <svg-icon class-name="search-icon" icon-class="shanchu" />
          删除
        </span>
      </template>
      <template v-slot:selectNamelist>
        火灾预警信息
      </template>
    </list_controller>
    <!-- 新增弹框 -->
    <teleport to="body">
      <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="660" :height="auto" v-model="state.addModal"
        resize :mask="true" showFooter>
        <template #title>
          <div class="w100 h100 fsc mask_title">{{state.modalTitle}}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="top">
              <el-row :gutter="20">
                <el-col :span="24">
                  <p class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>基本信息</span></p>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="火灾预报名称" prop="fireForecastName">
                    <el-input v-model="state.formData.fireForecastName" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <p class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>测点预报</span></p>
                </el-col>
                <el-col>
                  <el-form-item label="">
                    <el-checkbox v-for="item in state.checkboxList" @change="checkboxChange($event,item)"
                      v-model="item.status">{{item.name}}测点</el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-row :gutter="20" v-for="item in state.formData.nodeList">
                    <el-col :span="24">
                      <p class="mask_sub_title" style="margin-left: -10px;">
                        <span v-if="item.pointForecastType =='0'">温度测点</span>
                        <span v-else-if="item.pointForecastType =='1'">一氧化碳测点</span>
                        <span v-else>烟雾测点</span>
                      </p>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="测点编号">
                        <el-select clearable filterable v-model="item.pointCode" placeholder="请选择"
                          @change="pointModelNumChange($event,item.pointForecastType)">
                          <el-option v-for="itemsub in item.list" :key="itemsub.pointId" :label="itemsub.pointId"
                            :value="itemsub.pointId">
                            <span>{{ itemsub.pointId+'-'+itemsub.placeName }}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="安装地点">
                        <el-input disabled v-model="item.place" placeholder="请输入"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="预报值" prop="forecastValue">
                        <el-input v-if="item.pointForecastType =='2'" :disabled="item.pointForecastType =='2'"
                          v-model="item.forecastValue" placeholder="请输入"></el-input>
                        <el-input oninput="value =value.replace(/[^\-\d.]/g, '') .replace(/^\./g, '').replace(/\.{2,}/g,
'.').replace(/(\.\d+)\./g, '$1') .replace(/(-)\./g, '$1') .replace(/\-{2,}/g, '-')
.replace(/(\d+|\.)-/g, '$1') .replace(/-(0){2,}/g,'$1') .replace(/(-)0+(\d+)/g, '$1$2')
.replace(/^0+(\d)/, '$1') .replace(/(\.\d{2})\d*/, '$1')" v-else v-model="item.forecastValue" placeholder="请输入">
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="24">
                  <p class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>预报设置</span></p>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="持续分钟" prop="durationTime">
                    <el-select clearable filterable v-model="state.formData.durationTime" placeholder="请选择">
                      <el-option v-for="item in state.stationInNumList" :key="item" :label="item" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <p class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>措施</span></p>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="" prop="measure">
                    <el-input type="textarea" v-model="state.formData.measure" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </template>
        <template #footer>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </template>
      </vxe-modal>
    </teleport>
    <!-- 报警记录 -->
    <el-drawer v-model="state.drawerShow" direction="rtl" size="40%" close-on-click-modal :modal="true">
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title">
          <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>报警记录信息</span>
        </h4>
      </template>
      <template #default>
        <div class="recordObjBox">
          <div style="display: flex;align-items: center;">
            <span style="margin-right: 10px;">预警时间</span>
            <el-date-picker v-model="state.recordObj.time" type="datetimerange" start-placeholder="开始时间"
              end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss" />
            <el-button style="margin-left: 10px;" type="primary" @click="recordClick">选择</el-button>
          </div>
          <el-row :gutter="20">
            <el-col :span="24">
              <p>基础信息</p>
            </el-col>
            <el-col :span="12">
              <span>预报警名称: {{ state.formData.fireForecastName }}</span>
            </el-col>
            <el-col :span="12">
              <span>持续时间: {{ state.formData.durationTime }}</span>
            </el-col>
            <el-col :span="24">
              <p>预警测点</p>
            </el-col>
            <el-col style="padding-left: 0;" :span="24" v-if="state.formData.nodeList.length>0">
              <el-row :gutter="20" v-for="item in state.formData.nodeList" style="margin: 10px 0;">
                <el-col :span="7">
                  <span>{{ Number(item.pointForecastType)==0?'温度测点':Number(item.pointForecastType)==1?'一氧化碳测点':'烟雾测点' }}: {{ item.pointCode }}</span>
                </el-col>
                <el-col :span="9">
                  <span>安装地点: {{ item.place }}</span>
                </el-col>
                <el-col :span="8">
                  <span>预报值({{Number(item.pointForecastType)==0?'摄氏度':Number(item.pointForecastType)==1?'ppm':''}}): {{Number(item.pointForecastType)==0?'≥':Number(item.pointForecastType)==1?'≥':''}}{{ item.forecastValue }}</span>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="24" style="margin-top: 10px;">
              <vxe-table height="400" :data="state.recordObj.listTable" border="inner">
                <vxe-column field="startTime" title="预报警时间" width="300">
                  <template #default="{row}">
                    {{ dayjs(row.startTime).format('YYYY/MM/DD HH:mm:ss') }}-{{ dayjs(row.endTime).format('YYYY/MM/DD HH:mm:ss') }}
                  </template>
                </vxe-column>
                <vxe-column field="accumulationTime" title="预警时长" width="140">
                </vxe-column>
                <vxe-column field="temperature" title="温度(℃)">
                </vxe-column>
                <vxe-column field="carbonDioxide" title="一氧化碳(ppm)">
                </vxe-column>
                <vxe-column field="smoke" title="烟雾">
                </vxe-column>
              </vxe-table>
            </el-col>
          </el-row>
        </div>
      </template>
      <!-- <template #footer>
        <p>
          <el-button type="info">取消</el-button>
          <el-button type="primary">确定</el-button>
        </p>
      </template> -->
    </el-drawer>
  </div>
</template>
<script setup>
  import list_controller from "@/components/commonCom/list_controller";
  import {
    computed,
    reactive,
    onMounted
  } from "vue";
    import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    table_headers
  } from '@/components/commonCom/table_headers';
  import axios from "@/utils/request"
  import usePagesStore from '@/store/modules/pages'
  import {
    getsubstationmodel,
    getlistPointsBySensorName,
    getlistSitesList,
  } from '@/api/config'
  import _ from 'lodash'
  import dayjs from 'dayjs'
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore()
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP
  components: {
    list_controller
  }
  let state = reactive({
    recordObj: {
      time: [],
      listTable: []
    },
    checkboxList: [{
      name: '温度',
      pointForecastType: 0,
      status: false
    }, {
      name: '一氧化碳',
      pointForecastType: 1,
      status: false
    }, {
      name: '烟雾',
      pointForecastType: 2,
      status: false
    }],
    checkboxData: [],
    dialogVisiblepictureCardPreview: false,
    dialogImageUrl: '',
    options: {
      tableheads: computed(() => table_headers.configGasFire),
      listSS: [
        ],
      queryList: {
        dropdownUrl: '',
        querys: [],
        queryMap: new Map([
          ['sensorTypeId', 'safety_pointType'],
          ['deviceTypeId', 'safety_deviceType'],
          ['alarmTypeId', 'alarmType']
        ])
      },
      dataUrl: '/gas/fire/list',
      delUrl: '/gas/fire/del',
      addUrl: '/gas/fire/add',
      descUrl: '/gas/fire/getById',
      editUrl: '/gas/fire/modify',
    },
    // 表单
    addModal: false,
    modalTitle: '新增预报警',
    formRef: null,
    formData: {
      nodeList: []
    },
    rules: {
      fireForecastName: [{
        required: true,
        message: '请选择火灾预报名称',
        trigger: 'change'
      }],
      durationTime: [{
        required: true,
        message: '请选择持续分钟',
        trigger: 'change'
      }]
    },
    editId: undefined,
    stationmodelList: [],
    stationInNumList: [0, 0.5, 1, 3, 5, 10, 15, 20, 30],
    forecastTypeList: [
      '上限报警值', '下限报警值', '上下限报警值'
    ],
    stationOutNumList: [{

    }],
  })
  // 报警记录
  function recordClick() {
    if (state.recordObj.time.length > 0) {
      getobtainWarnFireInfo()
    } else {
      proxy.$modal.msgWarning('请先选择预警时间范围!');
    }

  }
  // 查看按钮
  function lookBtn(row) {
    state.drawerShow = true
    axios.post(state.options.descUrl, {
      id: row.id
    }).then(res => {
      if (res.code == 200) {
        state.formData = res.data
      }
    })

  }

  // 新增按钮
  function addBtn(row) {
    state.modalTitle = '新增预报警'
    state.addModal = true
    state.formData = {}
    state.editId = undefined
    state.checkboxList = state.checkboxList.map(item => {
      item.status = false
      return item
    })
    state.checkboxData = []
    state.formData.nodeList = []
  }
  // 编辑按钮
  function editBtn(row) {
    state.checkboxList.forEach(item => {
      item.status = false
    })
    state.modalTitle = '编辑预报警'
    state.addModal = true
    axios.post(state.options.descUrl, {
      id: row.id
    }).then(res => {
      if (res.code == 200) {
        state.formData = res.data
        if (res.data.nodeList.length > 0) {
          res.data.nodeList.forEach(itemar => {
            state.checkboxList.forEach(item => {
              if (itemar.pointForecastType == Number(item.pointForecastType)) {
                item.status = true
                itemar.list = item.list
                itemar.pointForecastType = item.pointForecastType
              }
            })
          })
        } else {
          state.checkboxList.forEach(item => {
            item.status = false
          })
        }
        state.checkboxData = res.data.nodeList
        state.editId = res.data.id
      }
    })
  }

  function deleteBtn(row) {
    let ids = []
    if (row != 'mul') {
      ids = [row.id]
    } else {
      if (store.records.length > 0) {
        ids = store.records.map(item => {
          return item.id
        })
      } else {
        proxy.$modal.msgWarning('请先勾选所要删除数据!');
      }
    }
 if (ids.length > 0) {
      ElMessageBox.confirm(
          '确定要删除该数据吗?',
          '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        .then(() => {
          axios.post(state.options.delUrl, ids).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              ElMessage({
                type: 'success',
                message: res.msg,
              })
              store.records = []
            }
          })

        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '删除取消',
          })
        })
    }

  }
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["formRef"].validate(valid => {
      if (valid) {
        if (state.formData.nodeList == 0) {
          proxy.$modal.msgWarning('请选择测点预报');
        } else {
          if (state.editId) {
            state.formData.id = state.editId
            delete state.formData.judgeCondition
            axios.post(state.options.editUrl, state.formData).then(res => {
              if (res.code == 200) {
                proxy.$refs['zujianname'].getData()
                state.addModal = false
                proxy.$modal.msgSuccess(res.msg);
              }
            })
          } else {
            axios.post(state.options.addUrl, state.formData).then(res => {
              if (res.code == 200) {
                proxy.$refs['zujianname'].getData()
                state.addModal = false
                proxy.$modal.msgSuccess(res.msg);
              }
            })
          }
        }
      }
    })
  }

  function cancel() {
    state.addModal = false
  }

  function getsubstationmodelList() {
    getlistSitesList().then(res => {
      state.stationmodelList = Object.keys(res.data).map(item => {
        return {
          label: res.data[item],
          value: item
        }
      })
    })

  }

  function getobtainWarnFireInfo() {
    axios.post('HisWarnFire/obtainWarnFireInfo', {
      fireStartTime: dayjs(state.recordObj.time[0]).format('YYYY-MM-DD HH:mm:ss.000'),
      fireEndTime: dayjs(state.recordObj.time[1]).format('YYYY-MM-DD HH:mm:ss.000')
    }).then(res => {
      if(res.data.list.length>0){
        state.recordObj.listTable = res.data.list[0].fireWarnDetailList
      }
    })
  }
  async function checkboxDataList() {
    for (let i = 0; i < state.checkboxList.length; i++) {
      let arr = await listPointsBySensorName(state.checkboxList[i].name)
      state.checkboxList[i].list = arr
    }
  }
  checkboxDataList()
  async function checkboxChange(e, item) {
    state.checkboxData.push({
      name: item.name,
      pointForecastType: item.pointForecastType,
      forecastValue: item.pointForecastType == '2' ? '有烟' : undefined,
      list: item.list,
      status: e
    })
    state.checkboxData.forEach(itemar => {
      if (itemar.pointForecastType == item.pointForecastType) {
        itemar.status = e
      }
    })
    state.checkboxData = _.uniqBy(state.checkboxData, 'pointForecastType')
    state.formData.nodeList = state.checkboxData.filter(function (itemarnode) {
      return itemarnode.status !== false
    });
  }

  function pointModelNumChange(val, pointForecastType) {
    state.formData.nodeList.forEach(item => {
      if (item.pointForecastType == pointForecastType) {
        item.list.forEach(itemsub => {
          if (itemsub.pointId == val) {
            item.place = itemsub.placeName
          }
        })
      }
    })

  }

  function listPointsBySensorName(e) {
    return new Promise(resolve => {
      getlistPointsBySensorName({
        sensorName: e,
        condition: e == '烟雾' ? "D%" : "A%"
      }).then(res => {
        resolve(res.data)
      })
    })
  }

  getsubstationmodelList()
</script>
<style lang="scss" scoped>
  .recordObjBox {
    font-size: 14px;
    color: rgba(62, 70, 79, 0.8);

    p {
      margin: 10px 0 !important;
      color: rgba(62, 70, 79, 1) !important;
      font-size: 16px !important;
      font-weight: 700;
    }
  }

  ::v-deep .el-drawer {
    .querycss {
      .fsc {
        &:nth-child(2) {
          display: none;
        }
      }
    }

    .table_box {
      .fsc {
        display: none;
      }
    }
  }
</style>